package com.company.eduorder.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.company.eduorder.entity.Order;
import com.company.eduorder.feign.course.CourseFeignService;
import com.company.eduorder.feign.user.UserFeignService;
import com.company.eduorder.mapper.OrderMapper;
import com.company.eduorder.service.OrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.company.servicebase.constant.OrderConstant;
import com.company.servicebase.to.order.CourseTo;
import com.company.servicebase.to.order.UserTo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * <p>
 * 订单 服务实现类
 * </p>
 *
 * @author testjava
 * @since 2020-04-23
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {

    @Resource
    private CourseFeignService courseFeignService;

    @Resource
    private UserFeignService userFeignService;

    @Override
    @Transactional
    public String saveOrder(String courseId, String id) {
        QueryWrapper<Order> wrapper = new QueryWrapper<>();
        wrapper.eq("course_id", courseId).eq("member_id", id);
        Order order = this.getOne(wrapper);

        if (order == null) {
            CourseTo courseTo = courseFeignService.getCourseById(courseId);
            UserTo userTo = userFeignService.getUserById(id);

            order.setCourseId(courseTo.getId());
            order.setCourseTitle(courseTo.getTitle());
            order.setCourseCover(courseTo.getCover());
            order.setTeacherName(courseTo.getTeacherName());
            order.setMemberId(userTo.getId());
            order.setMobile(userTo.getMobile());
            order.setNickname(userTo.getNickname());
            order.setStatus(OrderConstant.orderStatusConstant.CREATED.getCode());
            order.setPayType(OrderConstant.orderPayConstant.WX.getCode());

            this.save(order);
            return order.getId();
        }
        return order.getId();
    }

    @Override
    public boolean isBuyCourse(String courseId, String memberId) {
        QueryWrapper<Order> wrapper = new QueryWrapper<>();
        wrapper.eq("course_id", courseId).eq("member_id", memberId).eq("status",
                OrderConstant.orderStatusConstant.FINISH.getCode());
        Integer count = this.baseMapper.selectCount(wrapper);

        if (count == 0) {
            return false;
        }
        return true;
    }


}
